<template>
  <el-form :inline="true" :model="SearchParams" class="demo-form-inline">
    <el-form-item label="采购单号">
      <el-input
        v-model="SearchParams.ProcurementCode"
        placeholder="采购单号"
        clearable
      />
    </el-form-item>
    <el-form-item label="产品编号：">
      <el-input
        v-model="SearchParams.ProductCode"
        placeholder="产品编号："
        clearable
      />
    </el-form-item>
    <el-form-item label="产品名称：">
      <el-input
        v-model="SearchParams.ProductName"
        placeholder="产品名称："
        clearable
      />
    </el-form-item>
    <el-form-item label="订单状态">
      <el-select
        v-model="SearchParams.ProcurementState"
        placeholder="订单状态"
        size="large"
        style="width: 240px"
      >
        <el-option label="请选择" :value="0" />
        <el-option
          v-for="item in ProcureTable.options"
          :key="item.value"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="ShowProcureData">查询</el-button>
    </el-form-item>
  </el-form>

  <el-button type="primary" @click="save">添加</el-button>
  <el-table
    ref="multipleTableRef"
    :data="ProcureTable.tableData"
    style="width: 100%"
    @selection-change="handleSelectionChange"
  >
    <el-table-column type="selection" width="55" />
    <el-table-column property="ProcurementCode" label="订单号" />
    <el-table-column property="ProductName" label="产品名称" />
    <el-table-column property="ProductCode" label="产品编号" />
    <el-table-column property="Specs" label="产品规格" />
    <el-table-column property="UnitName" label="单位" />
    <el-table-column property="Price" label="单价" />
    <el-table-column property="BuyNumber" label="数量" />
    <el-table-column property="SumPrice" label="总额" />
    <el-table-column property="SupplierCode" label="供应商编号" />
    <el-table-column property="ProcurementStateText" label="状态" />
    <el-table-column property="ProcurementProcurement" label="是否入账" />
    <el-table-column property="IsReFund" label="退货" />
    <el-table-column property="CreateTime" label="创建时间" />
    <el-table-column label="Operations">
      <template #default="scope">
        <el-button size="small" @click="handleEdit(scope.row.Id)"
          >编辑</el-button
        >
        <el-button
          size="small"
          type="danger"
          @click="handleDelete(scope.row.ShoppingId)"
          >删除</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="handleReturn(scope.row.Id, scope.row.ShoppingId)"
          >退货</el-button
        >
      </template>
    </el-table-column>
  </el-table>

  <el-pagination
    v-model:current-page="SearchParams.pageIndex"
    v-model:page-size="SearchParams.pageSize"
    :page-sizes="[10, 20, 30, 40]"
    layout="total, sizes, prev, pager, next, jumper"
    :total="totalCount"
    @size-change="handleSizeChange"
    @current-change="handleCurrentChange"
  />

  <el-dialog
    v-model="dialogFormVisible"
    title="新增采购单"
    width="1000"
    v-if="dialogFormVisible"
  >
    <AddProcure ref="add" @closedialog="Closedialog" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisible = false">Cancel</el-button>
        <el-button type="primary" @click="saveData"> 确认 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="dialogFormVisibleEmit"
    title="编辑采购单"
    width="1000"
    v-if="dialogFormVisibleEmit"
  >
    <EmitProcure ref="emit" :Id="Id" @closedialog="Closedialog" />
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisibleEmit = false">取消</el-button>
        <el-button type="primary" @click="UpdateData"> 修改 </el-button>
      </div>
    </template>
  </el-dialog>

  <el-dialog
    v-model="dialogFormVisibleReturn"
    title="采购退货"
    width="1000"
    v-if="dialogFormVisibleReturn"
  >
    <el-form :model="form" label-width="auto" style="max-width: 800px">
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="订单号">
            <el-input v-model="form.ProcurementCode" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="单据类型">
            <el-select v-model="form.DocumentType" placeholder="单据类型">
              <el-option label="采购收货" :value="1" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="单据状态">
            <el-select
              v-model="form.DocumentState"
              placeholder="单据状态"
              size="large"
              style="width: 240px"
            >
              <el-option label="请选择" :value="0" />
              <el-option
                v-for="item in ProcureTable.options1"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="关联单号">
            <el-input v-model="form.SaleCode" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="制单人">
            <el-input v-model="form.UserName" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="制单日期">
            <el-date-picker v-model="form.UserTime" type="date" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="发货日期">
            <el-date-picker v-model="form.ShipmentsTime" type="date" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="供应商编号">
            <el-input v-model="form.SupplierCode" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="客户名称">
            <el-input v-model="form.ClientName" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8" :offset="0">
          <el-form-item label="联系人">
            <el-input v-model="form.ContactName" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="电话">
            <el-input v-model="form.Phone" />
          </el-form-item>
        </el-col>
        <el-col :span="8" :offset="0">
          <el-form-item label="备注">
            <el-input v-model="form.Remark" />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-table :data="ProcureTable.ReturntableData" style="width: 100%">
      <el-table-column property="ProductName" label="产品名称" />
      <el-table-column property="ProductCode" label="产品编号" />
      <el-table-column property="Specs" label="产品规格" />
      <el-table-column property="UnitName" label="单位" />
      <el-table-column property="BuyNumber" label="数量" />
      <el-table-column property="Price" label="单价" />
      <el-table-column property="ReturnNumber" label="退货数">
        <template #default="scope">
          <el-input v-model="scope.row.ReturnNumber" />
        </template>
      </el-table-column>
      <el-table-column property="ReturnSum" label="总额">
        <template #default="scope">
          {{ scope.row.Price * scope.row.ReturnNumber }}
        </template>
      </el-table-column>
    </el-table>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="dialogFormVisibleReturn = false">取消</el-button>
        <el-button type="primary" @click="ReturnNumberData"> 退货 </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref } from "vue";
import { ElTable } from "element-plus";
import AddProcure from "./AddProcure.vue";
import EmitProcure from "./EmitProcure.vue";
import {
  ShowProcure,
  ShowProcurementState,
  DelProcure,
  EmitProcureManage,
  GetDocumentState,
  EmitShopping1,
  InsertProcuremenReturn,
} from "@/api/Procure/index";
import { SearchProdureType } from "@/api/Procure/type";
import router from "@/router";

interface Form {
  ProcuremenId: number;
  ProductId: number;
  ProcurementCode: string;
  DocumentType: number;
  DocumentState: number;
  SaleCode: string;
  UserName: string;
  UserTime: string;
  ShipmentsTime: string;
  SupplierCode: string;
  ClientName: string;
  ContactName: string;
  Phone: string;
  Remark: string;
  ReturnNumber: number;
  Price: number;
}

const dialogFormVisible = ref(false);
const dialogFormVisibleEmit = ref(false);
const dialogFormVisibleReturn = ref(false);

const Closedialog = async () => {
  dialogFormVisible.value = false;
  await ShowProcureData();
  dialogFormVisibleEmit.value = false;
  await ShowProcureData();
};

const ProcureTable = reactive({
  tableData: [],
  options: [
    {
      value: "",
      label: "",
    },
  ],
  options1: [
    {
      value: "",
      label: "",
    },
  ],
  ReturntableData: [] as any[],
});
const totalCount = ref(0);

const SearchParams = reactive<SearchProdureType>({
  ProcurementCode: "",
  ProductCode: "",
  ProductName: "",
  ProcurementState: 0,
  pageIndex: 1,
  pageSize: 10,
});

interface Procure {
  ProcurementCode: string;
  ProductName: string;
  ProductCode: string;
  Specs: string;
  Unit: number;
  Price: number;
  BuyNumber: number;
  SumPrice: number;
}

const multipleTableRef = ref<InstanceType<typeof ElTable>>();
const multipleSelection = ref<Procure[]>([]);

const handleSelectionChange = (val: Procure[]) => {
  multipleSelection.value = val;
};

const save = () => {
  dialogFormVisible.value = true;
};

const add = ref();
const saveData = () => {
  add.value.submitForm("ruleFormRef");
};
const emit = ref();
const UpdateData = () => {
  emit.value.submitFormEmit("ruleFormRef");
};

const handleSizeChange = async (val: number) => {
  SearchParams.pageSize = val;
  await ShowProcureData();
};
const handleCurrentChange = async (val: number) => {
  SearchParams.pageIndex = val;
  await ShowProcureData();
};

const ShowProcureData = async () => {
  var res = await ShowProcure(SearchParams);
  if (res.code === 200) {
    ProcureTable.tableData = res.data.Item1;
    totalCount.value = res.data.Item2;
  }
};
const Id = ref(0);

const handleEdit = (index: number) => {
  dialogFormVisibleEmit.value = true;
  //console.log(index)
  Id.value = index;
};

const handleDelete = (index: number) => {
  ElMessageBox.confirm("确认要删除这条数据吗?", "Warning", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      var res = await DelProcure(index);
      if (res.code == 200) {
        ElMessage({
          type: "success",
          message: res.message,
        });
        await ShowProcureData();
      }
    })
    .catch(() => {
      ElMessage({
        type: "info",
        message: "取消删除",
      });
    });
};

const form = reactive<Form>({
  ProcuremenId: 0,
  ProductId: 0,
  ProcurementCode: "",
  DocumentType: 0,
  DocumentState: 1,
  SaleCode: "",
  UserName: "",
  UserTime: "",
  ShipmentsTime: "",
  SupplierCode: "",
  ClientName: "",
  ContactName: "",
  Phone: "",
  Remark: "",
  ReturnNumber: 0,
  Price: 0.0,
});

const handleReturn = async (index: number, index1: number) => {
  dialogFormVisibleReturn.value = true;
  form.ProcuremenId = index;
  var res = await EmitProcureManage(index);
  if (res.code == 200) {
    var data = res.data;
    console.log(data);
    Object.keys(form).forEach((key) => {
      if (key in data) {
        (form as any)[key] = data[key];
      }
    });
  }

  var res = await EmitShopping1(index1);
  if (res.code == 200) {
    var data = res.data;
    console.log(data);
    ProcureTable.ReturntableData = data;
  }
};

const ReturnNumberData = async () => {
  const firstRow = ProcureTable.ReturntableData[0];
  form.ProductId = firstRow.ProductId;
  form.ReturnNumber = firstRow.ReturnNumber;
  form.Price = firstRow.Price;
  console.log(form);
  var res = await InsertProcuremenReturn(form);
  if (res.code == 200) {
    ElMessage({
      type: "success",
      message: res.message,
    });
    router.push({ path: "ProcureReturn" });
  }
};

onMounted(async () => {
  await ShowProcureData();
  var res = await ShowProcurementState();
  if (res.code == 200) {
    ProcureTable.options = res.data;
  }
  var res = await GetDocumentState();
  if (res.code == 200) {
    ProcureTable.options1 = res.data;
  }
});
</script>
